package com.ailesson.order.api;

import com.ailesson.common.except.GlobalErrorCodeConstants;
import com.ailesson.common.except.ServiceException;
import com.ailesson.common.reply.R;
import com.ailesson.order.service.OrderInfoService;
import com.ailesson.order.service.WxPayMpService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Tag(name = "微信支付模块")
@RestController
@RequestMapping("/api/order/wxPay")
public class WxMpPayController {
    @Autowired
    private WxPayMpService wxPayService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Operation(summary = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderNo}")
    public R queryPayStatus(@PathVariable("orderNo") String orderNo) {
        //根据订单号调用微信接口查询支付状态
        Map<String,String> resultMap = wxPayService.queryPayStatus(orderNo);
        //判断支付是否成功：根据微信支付状态接口判断
        if(resultMap == null) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"支付出错");
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {//成功
            //更新订单状态 ：已经支付
            String out_trade_no = resultMap.get("out_trade_no");
            orderInfoService.updateOrderStatus(out_trade_no);
            return R.success();
        }
        return R.success("支付中");
    }

    @Operation(summary = "下单支付")
    @GetMapping("/createJsapi/{orderNo}")
    public R createJsapi(@PathVariable("orderNo") String orderNo) {
        Map<String,Object> map = wxPayService.createJsapi(orderNo);
        return R.success(map);
    }
}
